// pages/overhaulAdd/overhaulAdd.js
const app = getApp();
import CommonService from '../../utils/service/commonService.js';
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast';
const util = require('../../utils/util');
import Base64 from '../../utils/Base64.js';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //传参来的设备信息
    equipmentInfo:null,
    //提交按钮禁用
    disabled:false,
    //检修人员选择框
    showServiceName:false,
    //检修人员选择数据
    serviceNameList:[],
    //上传的图片
    imgUrls:[],
    //传参来的id
    id:null,
    //是否是修改
    isEdit:false,
    //修改信息回显
    editInfo:{},
    //全选/反选
    checkedAll: false,
    //检修明细选项
    checkDetail: [],
    //检修明细选项的数量
    checkLen:7,
    //检修时间
    overhaulDate:util.timeFormat(new Date()),
    //检修时间选择框
    showTime:false,
    maxDate: new Date().getTime(),
    currentDate: new Date().getTime(),
    formatter (type, value) {
      if (type === 'year') {
        return `${value}年`
      } else if (type === 'month') {
        return `${value}月`
      } else if (type === 'day') {
        return `${value}日`
      } else if (type === 'hour') {
        return `${value}时`
      } else if (type === 'minute') {
        return `${value}分`
      } else if (type === 'second') {
        return `${value}秒`
      }
      return value
    },
    //检修详情
    detailList:[],
    //是否单个设备
    isOne:false,
    //设备编码
    equipmentNo:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if(options.paramObj && options.paramObj!='null'){
      this.setData({
        equipmentInfo: JSON.parse(options.paramObj),
        isOne:true
      })
    }

    if(options.id){
      this.setData({
        id: parseInt(options.id),
        isEdit:true
      })

      wx.setNavigationBarTitle({
        title: '修改检修'
      })

      //查询检修人员
      this.getServiceNameList();
    }

    //查询检修详情
    this.overhaulDetail();
  },

  //提交表单
  confirmForm(e){
    //避免表单重复提交-先禁用按钮
    this.setData({
      disabled:true
    })

    let obj=e.detail.value;
    let td=this.data;
    let flag=true;

    //验证设备
    if(!this.data.isOne){
      let equipmentNo=obj.equipmentNo.trim();

      //非空验证
      if(!this.formNotEmpty(equipmentNo,'equipmentNoMessage','请输入设备编码')){
        return;
      }

      //验证设备是否存在
      flag=this.isExist(equipmentNo).then(value =>{
        if(!value){
          this.setData({
            equipmentNoMessage: '此设备不存在',
            disabled:true
          })
        }
        return value;
      });
    }

    //检修人员验证
    if(!td.editInfo.overhaulPersonnel){
      Toast.fail('请选择检修人员');
      return;
    }

    //费用是数值
    if(obj.partMoney!='' && obj.partMoney!=null){
      if(!(/^\d+(\.\d+)?$/.test(obj.partMoney))){
        this.setData({
          partMoneyMessage: '请输入数字',
          disabled: true
        });
        return;
      }
    }

    if(obj.serviceMoney!='' && obj.serviceMoney!=null){
      if(!(/^\d+(\.\d+)?$/.test(obj.serviceMoney))){
        this.setData({
          serviceMoneyMessage: '请输入数字',
          disabled: true
        });
        return;
      }
    }

    if(obj.logisticsMoney!='' && obj.logisticsMoney!=null){
      if(!(/^\d+(\.\d+)?$/.test(obj.logisticsMoney))){
        this.setData({
          logisticsMoneyMessage: '请输入数字',
          disabled: true
        });
        return;
      }
    }

    //处理图片格式
    let pics=td.imgUrls;
    let picArr=[];
    if(pics && pics.length){
        pics.forEach(item => {
            picArr.push({
          url:item
        });
      });
    }

    //处理检修明细
    let checkDetailStr=td.checkDetail;
    let checkDetail=[];
    checkDetailStr.forEach(item => {
		  checkDetail.push(parseInt(item));
    });

    Promise.all([flag]).then(value => {
      let passed=value.every(val=>{
        return val;
      });

      if(passed){
        let dataObj={};
        if(this.data.isEdit){
          //编辑
          dataObj={
            id:this.data.id,
            overhaulDate:td.overhaulDate,
            overhaulPersonnel: td.editInfo.overhaulPersonnel,
            equipmentState:obj.equipmentState.trim(),
            detail:checkDetail,
            result:obj.result.trim(),
            partMoney:Number(obj.partMoney),
            serviceMoney:Number(obj.serviceMoney),
            logisticsMoney:Number(obj.logisticsMoney),
            pic:JSON.stringify(picArr),
            remark:obj.remark.trim(),
            appId: [app.globalData.myAppId]
          }
        }else{
          //添加
          dataObj={
            departId:td.equipmentInfo.projectId,
            userId:app.globalData.userInfo.id,
            overhaulDate:td.overhaulDate,
            overhaulPersonnel: td.editInfo.overhaulPersonnel,
            equipmentState:obj.equipmentState.trim(),
            detail:checkDetail,
            result:obj.result.trim(),
            partMoney:Number(obj.partMoney),
            serviceMoney:Number(obj.serviceMoney),
            logisticsMoney:Number(obj.logisticsMoney),
            pic:JSON.stringify(picArr),
            equipmentId:td.equipmentInfo.equipmentId,
            remark:obj.remark.trim(),
            appId: [app.globalData.myAppId],
            dataAuthority:{
                depart: [td.equipmentInfo.projectId]
            }
          }
        }

        let param={
          className:'afterSaleOverhaul',
          data:dataObj
        }

        //避免表单重复提交
        Toast.loading({
          duration: 0,
          forbidClick: true,
          message: '数据提交中...'
        });
        //console.log(param);

        CommonService.goSave(param).then(res=>{
          this.setData({
            disabled:false
          })
          if (res.statusCode == 200 && res.data.success == true){
            Toast.success('成功');
            setTimeout(() => {
              //返回列表页并刷新数据
              this.backAndRefresh();
            }, 1000);
          }else if(res.statusCode==202){
            Toast.fail('您操作太快了,请勿重复提交');
          }else{
            Toast.fail('操作失败');
          }
        }).catch((error) => {
          Toast.fail('操作失败');
        })

      }
    });
  },

  //非空验证（field要先去掉空格）
  formNotEmpty(field,messageField,messageCon){
    if(!field){
      let obj = {};
      obj[messageField] = messageCon;
      obj['disabled'] = true;
      this.setData(obj);
      return false;
    }else{
      return true;
    }
  },

  //验证数据重复
  isExist(data){
    let param={
      isAuth:false,
      className:'equipment',
      data:{
        equipmentNo:data,
        nbl:Base64.encode(util.timeFormatDay(new Date())),
        selectFields:["id",'projectId','equipmentId']
      }
    }

    return new Promise((resolve, reject) => {
      CommonService.goFindList(param).then(res=>{
        if (res.data.data && res.data.data.count && res.data.data.result) {
          let obj=res.data.data.result[0];
          let equipmentInfo={
            projectId:obj.memberId,
            equipmentId:obj.id
          }
          this.setData({
            equipmentInfo: equipmentInfo
          })
          resolve(true);
        } else {
          resolve(false);
        }
      }).catch((error) => {
        resolve(false);
      })
    });
  },

  //用户输入时清除错误提示
  clearMessage(e) {
    let field = e.target.dataset.message;
    let obj = {};
    obj[field] = "";
    obj['disabled'] = false;
    this.setData(obj);
  },

  //获取图片上传组件的传值
  getUploadUrl(data){
    let imgUrls=data.detail;

    if(imgUrls.length){
      this.setData({
        imgUrls: imgUrls
      })
    }else{
        this.setData({
            imgUrls: null
        }) 
    }
  },

  //获取要修改的数据
  getInfo(){
    let param = {
      isAuth: false,
      className: 'afterSaleOverhaul',
      data: {
        id:this.data.id,
        selectFields: ['id','departId','depart','overhaulPersonnel','service','overhaulDate','partMoney','serviceMoney','logisticsMoney','pic','equipmentState','remark','result','detail','equipmentObj']
      }
    }

    CommonService.goFindList(param).then(res => {
      if(res.data.data && res.data.data.result && res.data.data.result.length) {
        let result=res.data.data.result[0];

        //处理检修人员
        let arr2=this.data.serviceNameList;
        if(result.overhaulPersonnel && arr2.length){
          arr2.forEach(item => {
            if(item.id==result.overhaulPersonnel){
              result.self_overhaulPersonnel=item.text;
            }
          });
        }

        this.setData({
          editInfo: result
        })

        //修改信息回显
        this.getInputValue();
      }
    }).catch((error) => {
    })
  },

  //修改信息回显
  getInputValue(){
    let info=this.data.editInfo;

    console.log('修改信息回显');
    console.log(info);

    //处理详情选项
    let detail=info.detail;
    let arr=[];
    detail.forEach(item => {
      arr.push(item+'');
    });

    //处理图片
    let pic=JSON.parse(info.pic);
    let picArr=[];
    pic.forEach(item => {
      picArr.push(item.url);
    });

    this.setData({
        overhaulDate: info.overhaulDate ? util.timeFormat(info.overhaulDate) : null,
        checkDetail:arr,
        imgUrls:picArr,
        equipmentNo: info.equipmentObj.length && info.equipmentObj[0].equipmentNo ? info.equipmentObj[0].equipmentNo : ''
      })
  },

  //返回列表页并刷新数据
  backAndRefresh(){
    let pages = getCurrentPages();
    let prevPage = pages[pages.length - 2];

    prevPage.refreshListAndPage();
    wx.navigateBack();
  },

  //点击全选
  onChangeAll(event) {
    this.setData({
      checkedAll: event.detail,
    })

    if(event.detail){
      let list=this.data.detailList;
      let arr=[];
      list.forEach(item => {
        arr.push(item.id+'');
      })
      this.setData({
        checkDetail: arr,
      })
    }else{
      this.setData({
        checkDetail: [],
      })
    }
  },

  //点击明细选项
  onChangeDetail(event) {
    this.setData({
      checkDetail: event.detail,
    })

    if(event.detail.length==this.data.checkLen){
      this.setData({
        checkedAll: true,
      })
    }else{
      this.setData({
        checkedAll: false,
      })
    }
  },

  //显示检修人员选择框
  onShowServiceName(){
    this.setData({
			showServiceName: true
    }) 
    //查询检修人员
    this.getServiceNameList2(); 
  },

  //查询检修人员
  getServiceNameList(){
    let param = {
      isAuth: false,
      className: 'servicePersonal',
      data: {
        searchAll: true,
        selectFields: ['id','serviceName'],
        sort: {
          id: -1
        }
      }
    }

    //按平台查询记录
    let appId=app.globalData.myAppId;
    if(appId!=3){
      if(app.globalData.afterSaleSelf){
        //是否独立售后
        param.data.appId=app.globalData.myAppId;
      }else{
        param.data.appId=[2,3,null];
      }
    }else{
      param.data.appId=[2,3,null];
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let arr=[];
        result.forEach(item => {
          arr.push({
            text:item.serviceName,
            id:item.id
          });
        });
        this.setData({
          serviceNameList: arr
        })

        //获取要修改的数据
        this.getInfo();
      }
    }).catch((error) => {
    })
  }, 
  
   //查询检修人员
   getServiceNameList2(){
    this.setData({
      serviceNameList: []
    })

    let param = {
      isAuth: false,
      className: 'servicePersonal',
      data: {
        searchAll: true,
        selectFields: ['id','serviceName'],
        sort: {
          id: -1
        }
      }
    }

    //按平台查询记录
    let appId=app.globalData.myAppId;
    if(appId!=3){
      if(app.globalData.afterSaleSelf){
        //是否独立售后
        param.data.appId=app.globalData.myAppId;
      }else{
        param.data.appId=[2,3,null];
      }
    }else{
      param.data.appId=[2,3,null];
    }

    //人员模糊查询
    if(this.data.valueSearch){
      param.data.serviceName='%' + this.data.valueSearch + '%';
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let arr=[];
        result.forEach(item => {
          arr.push({
            text:item.serviceName,
            id:item.id
          });
        });
        this.setData({
          serviceNameList: arr
        })  
      }
    }).catch((error) => {
    })
  },

  //隐藏检修人员选择框
  onCloseServiceName(){
    this.setData({
			showServiceName: false
    })
  },

  //确认检修人员
  onConfirmServiceName(e){
    let overhaulPersonnel='editInfo.overhaulPersonnel';
    let self_overhaulPersonnel='editInfo.self_overhaulPersonnel';

    this.setData({
      [overhaulPersonnel]: e.detail.value.id,
      [self_overhaulPersonnel]: e.detail.value.text,
      disabled: false
    })
    this.onCloseServiceName();
  },

  //显示检修时间选择框
  onShowTime(){
    this.setData({
			showTime: true
    })
  },

  //隐藏检修时间选择框
  onCloseTime(){
    this.setData({
			showTime: false
    })
  },

  //确认检修时间
  onConfirmTime(e) {
    this.setData({
      currentDate: e.detail,
      overhaulDate:util.timeFormat(e.detail),
    });
    this.onCloseTime();
  },

  //查询检修详情字典
  overhaulDetail(){
    let param1 = {
      isAuth: false,
      className: 'dictionary',
      data: {
        searchAll: true,
        key: 'overhaul',
        selectFields: ['id']
      }
    }

    CommonService.goFindList(param1).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let dictionaryId = res.data.data.result[0].id;

        let param2 = {
          isAuth: false,
          className: 'dictionaryDetail',
          data: {
            searchAll: true,
            dictionaryId: dictionaryId,
            selectFields: ['id','fieldValue']
          }
        }
        CommonService.goFindList(param2).then(res2=>{
          if(res2.data.data && res2.data.data.result && res2.data.data.result.length){
            let dictionaryDetails=res2.data.data.result;
            let arr=[];
            dictionaryDetails.forEach(detail => {
              arr.push({
                id: detail.id,
                name: detail.fieldValue
              });
            })

            this.setData({
              detailList: arr,
              checkLen:arr.length
            });
          }
        }).catch((error) => {
        })
      }

    }).catch((error) => {
    })
  },

   //搜索检修人员
   onChangeSelectVal(e){
    this.setData({
      valueSearch: e.detail
    })
    this.getServiceNameList2();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  }
})
